package com.pinyoumei.app.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.AddressManagementActivity;
import com.pinyoumei.app.activity.BalanceOrderListActivity;
import com.pinyoumei.app.activity.CouponListActivity;
import com.pinyoumei.app.activity.LuckPanActivity;
import com.pinyoumei.app.activity.LuckyValueActivity;
import com.pinyoumei.app.activity.MessageActivity;
import com.pinyoumei.app.activity.NewUserHelperActivity;
import com.pinyoumei.app.activity.PTGroupCouponActivity;
import com.pinyoumei.app.activity.PTOrderSelectActivity;
import com.pinyoumei.app.activity.ReNameActivity;
import com.pinyoumei.app.activity.SettingActivity;
import com.pinyoumei.app.activity.SignInActivity;
import com.pinyoumei.app.activity.TeamAdvancedActivity;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.activity.ZBkOrderListActivity;
import com.pinyoumei.app.activity.integral.IntegralOrderListActivity;
import com.pinyoumei.app.activity.userpersonal.MyPerformanceActivity;
import com.pinyoumei.app.activity.wallet.WalletHostActivity;
import com.pinyoumei.app.bean.FourBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.utils.event.UserEvent;
import com.pinyoumei.app.view.BadgeView;
import com.pinyoumei.app.view.LoadingDailog;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;


@SuppressLint("ValidFragment")
public class FourFragment extends BaseLazyLoadFragment implements View.OnClickListener {
    private String mTitle;
    private LoadingDailog loadingDailog;
    private Gson gson;
    private String kf_url = "";
    private BadgeView badgeView;
    private CircleImageView iv_user_head_img;
    private TextView tv_user_real_name;
    private TextView tv_recommand_code;
    private ImageView tv_level_name;
    private TextView tv_user_make_money;
    private TextView tv_user_lucky_num;
    private TextView tv_user_group_coupon;
    private TextView tv_coupon_num;
    private TextView tv_today_profit;
    private TextView tv_total_profit;
    private TextView tv_pt_profit;
    private TextView tv_group_buy_profit;
    private TextView tv_return_profit;
    private TextView tv_total_direct_num;
    private TextView tv_today_direct_num;
    private TextView tv_total_team_num;
    private TextView tv_today_team_num;
    private TextView tv_hp_order_num;
    private TextView tv_hp_order_amount;
    private TextView tv_return_profit_order_num;
    private TextView tv_return_profit_order_amount,tv_recommand_copy;
    private int is_verify = -1;
    private String recommandCode = "";

    public static FourFragment getInstance(String title) {
        FourFragment sf = new FourFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_four;
    }

    @Override
    public void initView(View rootView) {
        EventBusUtils.register(this);
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();

        LinearLayout ll_setting = rootView.findViewById(R.id.ll_setting);
        ll_setting.setOnClickListener(this);
        LinearLayout ll_kefu = rootView.findViewById(R.id.ll_kefu);
        ll_kefu.setOnClickListener(this);
        LinearLayout ll_message = rootView.findViewById(R.id.ll_message);
        ll_message.setOnClickListener(this);
        TextView tvRecommandCopy = rootView.findViewById(R.id.tv_recommand_copy);
        tvRecommandCopy.setOnClickListener(this);
        Button bt_withdraw = rootView.findViewById(R.id.bt_withdraw);
        bt_withdraw.setOnClickListener(this);

        LinearLayout ll_luck = rootView.findViewById(R.id.ll_luck);
        ll_luck.setOnClickListener(this);
        LinearLayout ll_pt = rootView.findViewById(R.id.ll_pt);
        ll_pt.setOnClickListener(this);
        LinearLayout ll_coupon = rootView.findViewById(R.id.ll_coupon);
        ll_coupon.setOnClickListener(this);
        LinearLayout ll_daifahuo = rootView.findViewById(R.id.ll_daifahuo);
        ll_daifahuo.setOnClickListener(this);
        RelativeLayout rl_jifen = rootView.findViewById(R.id.rl_jifen);
        rl_jifen.setOnClickListener(this);

        LinearLayout ll_is_fahuo = rootView.findViewById(R.id.ll_is_fahuo);
        ll_is_fahuo.setOnClickListener(this);

        LinearLayout ll_is_finish = rootView.findViewById(R.id.ll_is_finish);
        ll_is_finish.setOnClickListener(this);



        //设置小红点的大小以及颜色
        badgeView = new BadgeView(getActivity());
        badgeView.setTargetView(ll_message);//将小红点依附于该布局之上
        badgeView.setBackground(12, Color.parseColor("#FF2222"));//设置小红点的大小以及颜色
        badgeView.setTextColor(Color.parseColor("#FFFFFF"));
        badgeView.setBadgeGravity(Gravity.TOP | Gravity.RIGHT);
        badgeView.setBadgeMargin(0, 5, 5, 0);

        iv_user_head_img = rootView.findViewById(R.id.iv_user_head_img);
        tv_user_real_name = rootView.findViewById(R.id.tv_user_real_name);
        tv_recommand_code = rootView.findViewById(R.id.tv_recommand_code);
        tv_level_name = rootView.findViewById(R.id.tv_level_name);
        tv_user_make_money = rootView.findViewById(R.id.tv_user_make_money);
        tv_user_lucky_num = rootView.findViewById(R.id.tv_user_lucky_num);
        tv_user_group_coupon = rootView.findViewById(R.id.tv_user_group_coupon);
        tv_coupon_num = rootView.findViewById(R.id.tv_coupon_num);
        tv_today_profit = rootView.findViewById(R.id.tv_today_profit);
        tv_total_profit = rootView.findViewById(R.id.tv_total_profit);
        tv_pt_profit = rootView.findViewById(R.id.tv_pt_profit);
        tv_group_buy_profit = rootView.findViewById(R.id.tv_group_buy_profit);
        tv_return_profit = rootView.findViewById(R.id.tv_return_profit);
        tv_total_direct_num = rootView.findViewById(R.id.tv_total_direct_num);
        tv_today_direct_num = rootView.findViewById(R.id.tv_today_direct_num);
        tv_total_team_num = rootView.findViewById(R.id.tv_total_team_num);
        tv_today_team_num = rootView.findViewById(R.id.tv_today_team_num);
        tv_hp_order_num = rootView.findViewById(R.id.tv_hp_order_num);
        tv_hp_order_amount = rootView.findViewById(R.id.tv_hp_order_amount);
        tv_return_profit_order_num = rootView.findViewById(R.id.tv_return_profit_order_num);
        tv_return_profit_order_amount = rootView.findViewById(R.id.tv_return_profit_order_amount);





        LinearLayout ll_recharge = rootView.findViewById(R.id.ll_recharge);
        ll_recharge.setOnClickListener(this);
        LinearLayout ll_order = rootView.findViewById(R.id.ll_order);
        ll_order.setOnClickListener(this);
        LinearLayout mLl1 = rootView.findViewById(R.id.ll_1);
        mLl1.setOnClickListener(this);
        LinearLayout  mLl2 = rootView.findViewById(R.id.ll_2);
        mLl2.setOnClickListener(this);
        LinearLayout mLl3 = rootView.findViewById(R.id.ll_3);
        mLl3.setOnClickListener(this);
        LinearLayout mLl4 = rootView.findViewById(R.id.ll_4);
        mLl4.setOnClickListener(this);
        LinearLayout mLl5 = rootView.findViewById(R.id.ll_5);
        mLl5.setOnClickListener(this);
        LinearLayout  mLl6 = rootView.findViewById(R.id.ll_6);
        mLl6.setOnClickListener(this);
        LinearLayout  mLl7 = rootView.findViewById(R.id.ll_7);
        mLl7.setOnClickListener(this);
        LinearLayout mLl8 = rootView.findViewById(R.id.ll_8);
        mLl8.setOnClickListener(this);
        LinearLayout mLl9 = rootView.findViewById(R.id.ll_9);
        mLl9.setOnClickListener(this);

        SmartRefreshLayout swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setEnableLoadMore(false);
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                InitData();
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
        InitData();
    }



    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onMessageEventMain(UserEvent event) {
        if (event != null ) {
            InitData();
        }
    }



    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));


        OkGo.<String>post(Constants.USER_CENTER)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        FourBean fourBean = gson.fromJson(response.body(), FourBean.class);

                        if (fourBean.getCode() >= 0) {
                            kf_url = fourBean.getResult().getKf_url();
                            Constants.KF_URL = fourBean.getResult().getKf_url();
                            badgeView.setBadgeCount(fourBean.getResult().getNotice_count()+"");

                            FourBean.ResultBean.UserInfoBean user_info = fourBean.getResult().getUser_info();
                            if (user_info!=null){
                                is_verify  =user_info.getIs_verify();
                            }

                            Glide.with(getActivity()).load(user_info.getUser_head_img()).into(iv_user_head_img);
                            tv_user_real_name.setText(user_info.getUser_nick_name());
                            tv_recommand_code.setText("邀请码：" + user_info.getRecommand_code());
                            recommandCode = user_info.getRecommand_code();
//                            if(TextUtils.equals(user_info.getLevel_name(),"V4") || TextUtils.equals(user_info.getLevel_name(),"V5")){
//                                tv_level_name.setText("V3");
//                            }else {
//                                tv_level_name.setText(user_info.getLevel_name());
//                            }
                            tv_level_name.setImageDrawable(getResources().getDrawable(Utils.getLevelIcon(user_info.getLevel_name())));
                            tv_user_make_money.setText("¥" + user_info.getUser_make_money());
                            tv_user_lucky_num.setText( user_info.getUser_lucky_num()+"");
                            tv_user_group_coupon.setText( user_info.getUser_group_coupon()+"");
                            tv_coupon_num.setText( user_info.getCoupon_num()+"张");

                            tv_today_profit.setText( fourBean.getResult().getToday_profit()+"");
                            tv_total_profit.setText( fourBean.getResult().getTotal_profit()+"");
                            tv_pt_profit.setText( fourBean.getResult().getPt_profit()+"");
                            tv_group_buy_profit.setText( fourBean.getResult().getGroup_buy_profit()+"");
                            tv_return_profit.setText( fourBean.getResult().getReturn_profit()+"");

                            tv_total_direct_num.setText( fourBean.getResult().getTotal_direct_num()+"");
                            tv_today_direct_num.setText( "+" + fourBean.getResult().getToday_direct_num());
                            tv_total_team_num.setText( fourBean.getResult().getTotal_team_num()+"");
                            tv_today_team_num.setText( "+" +fourBean.getResult().getToday_team_num());
                            tv_hp_order_num.setText( fourBean.getResult().getHp_order_num()+"");
                            tv_hp_order_amount.setText( fourBean.getResult().getHp_order_amount()+"");
                            tv_return_profit_order_num.setText( fourBean.getResult().getReturn_profit_order_num()+"");
                            tv_return_profit_order_amount.setText( fourBean.getResult().getReturn_profit_order_amount()+"");

                        } else {
                            Toast.makeText(getActivity(), fourBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.ll_setting:
                startActivity(new Intent(getActivity(), SettingActivity.class));
        		break;

        		case R.id.ll_kefu:
                    if (!TextUtils.isEmpty(kf_url)){
                        final Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra("order_title", "");
                        intent.putExtra("url",kf_url);
                        startActivity(intent);
                    }
        		break;

        		case R.id.ll_message:
                    startActivity(new Intent(getActivity(), MessageActivity.class));
        		break;
                case R.id.tv_recommand_copy:
                    Utils.copy(recommandCode,getContext());
                    break;
        		case R.id.ll_luck:
        		    //幸运值
                    startActivity(new Intent(getActivity(), LuckyValueActivity.class));
        		break;

        		case R.id.ll_pt:
                    //开心值
                    startActivity(new Intent(getActivity(), PTGroupCouponActivity.class));
        		break;

        		case R.id.ll_coupon:
                    //优惠券
                    startActivity(new Intent(getActivity(), CouponListActivity.class));
        		break;

        		case R.id.ll_recharge:
//                    startActivity(new Intent(getActivity(), BalanceOrderListActivity.class));
                    startActivity(new Intent(getActivity(), IntegralOrderListActivity.class));
        		break;

        		case R.id.ll_order:
                    startActivity(new Intent(getActivity(), PTOrderSelectActivity.class));
        		break;

        		case R.id.bt_withdraw:
//                    startActivity(new Intent(getActivity(), RechargeActivity.class));
//                    startActivity(new Intent(getActivity(), BalanceActivity.class));
                    startActivity(new Intent(getActivity(), WalletHostActivity.class));
        		break;

        		case R.id.ll_daifahuo:
        		    Intent intent = new Intent(getActivity(), ZBkOrderListActivity.class);
                    intent.putExtra("tab_type",1);
                    startActivity(intent);
        		break;
        		case R.id.ll_is_fahuo:
        		    Intent intent2 = new Intent(getActivity(), ZBkOrderListActivity.class);
                    intent2.putExtra("tab_type",2);
                    startActivity(intent2);
        		break;
        		case R.id.ll_is_finish:
        		    Intent intent3 = new Intent(getActivity(), ZBkOrderListActivity.class);
                intent3.putExtra("tab_type",3);
                    startActivity(intent3);
        		break;

	            case R.id.ll_1:
                    //新手指南
                    startActivity(new Intent(getActivity(), NewUserHelperActivity.class));
        		break;
            case R.id.ll_2:
                //实名认证 是否已实名认证 0否 1是
                switch (is_verify) {
                	case 0:
                	    Intent intent1 = new Intent(getActivity(), ReNameActivity.class);
                        intent1.putExtra("kf_url",kf_url);
                        startActivity(intent1);
                		break;
                    case 1:
                        ToastUtils.showShort("您已认证，如需修改请联系客服");
                        break;
                	default:
                		break;
                }
                break;
            case R.id.ll_3:
            case R.id.rl_jifen:
                //团队进阶
                startActivity(new Intent(getActivity(), TeamAdvancedActivity.class));
                break;
            case R.id.ll_4:
                //客服
                if (!TextUtils.isEmpty(kf_url)){
                    final Intent intent4 = new Intent(getActivity(), WebViewActivity.class);

                    intent4.putExtra("order_title", "联系客服");
                    intent4.putExtra("url",kf_url);
                    startActivity(intent4);
                }
                break;
            case R.id.ll_5:
                //转盘
                startActivity(new Intent(getActivity(), LuckPanActivity.class));
                break;
            case R.id.ll_6:
                //签到
                startActivity(new Intent(getActivity(), SignInActivity.class));
                break;
            case R.id.ll_7:
                //地址
                startActivity(new Intent(getActivity(), AddressManagementActivity.class));
                break;
            case R.id.ll_8:
                //开店
                ToastUtils.showShort("敬请期待");
                break;
            case R.id.ll_9:
                //我的业绩
//                ToastUtils.showShort("敬请期待");
                startActivity(new Intent(getActivity(), MyPerformanceActivity.class));
                break;

        	default:
        		break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    EventBusUtils.unregister(this);
    }
}